package com.fjd.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.time.LocalDateTime;
import java.util.*;

/**
 * WebSocket服务类
 */
@Component
@ServerEndpoint("/shopping/ws/{from}/{to}")
public class WebSocketServer {
    private static Logger L = (Logger) LoggerFactory.getLogger(WebSocketServer.class);

    //存放会话对象
    private static List<SessionWrap> sessionList = new ArrayList<>();

    private String from;

    private String to;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("from") String from, @PathParam("to") String to) {
        System.out.println("from：" + from + " to：" + to);
        this.from = from;
        this.to = to;
        for (SessionWrap sessionWrap : sessionList) {
            if (sessionWrap.getFrom().equals(from) && sessionWrap.getTo().equals(to)) {
                sessionWrap.setSession(session);
                return ;
            }
        }
        SessionWrap sessionWrap = SessionWrap.builder()
                .from(from)
                .to(to)
                .session(session)
                .lastTime(LocalDateTime.now())
                .build();
        sessionList.add(sessionWrap);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到来自客户端：" + "from：" + from + "to：" + to + " 的信息:" + message);
        try {
            //发送到对方
            for (SessionWrap sessionWrap : sessionList) {
                if (sessionWrap.getFrom().equals(to) && sessionWrap.getTo().equals(from)) {
                    sessionWrap.getSession().getBasicRemote().sendText(message);
                    System.out.println("发送来自客户端：" + "from：" + from + "to：" + to + " 的信息:" + message);
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     *
     */
    @OnClose
    public void onClose() {
        System.out.println("连接断开:" + "from：" + from + "to" + to);
        List<SessionWrap> newSessionList = new ArrayList<>();
        for (SessionWrap sessionWrap : sessionList) {
            if (sessionWrap.getFrom().equals(from) && sessionWrap.getTo().equals(to)) {
                continue;
            }
            newSessionList.add(sessionWrap);
        }
        sessionList = newSessionList;
    }

}
